var logger = require('../../common/logger');
var Eventproxy = require('eventproxy');
var User = require('../../proxy').User;

/*
 * 授权中间件
 */
var authorize = function authorize(req, res, next) {
  var ep = new Eventproxy();
  ep.fail(next);
  var oauth2 = req.get('Authorization');
  if (!oauth2) {
    res.status(401);
    return res.send_data({
      code: 401,
      message: 'wrong clientType or pcode'
    });
  }
  var authPcode = oauth2.split(' ')[0];
  if (authPcode === 'OAuth2') {
    var pcode = oauth2.split(' ')[1];
    if (pcode) {
      pcode = new Buffer(pcode, 'base64').toString().split(':');
      var clientType = pcode[0];
      pcode = pcode[1];
      logger.info('clientType: ' + clientType);
      logger.info('pcode:' + pcode);
      User.findByUnameOrPcode({
        pcode: pcode
      }).then(function (user) {
        if (!user || ['1', '2'].indexOf(clientType) < 0) {
          res.status(401);
          return res.send_data({
            code: 401,
            message: 'wrong clientType or pcode'
          });
        }
        req.clientType = clientType;
        req.pcode = pcode;
        req.user = user;
        next();
      });
    }
  } else {
    res.status(401);
    return res.send_data({
      code: 401,
      message: 'wrong type of Authorization'
    });
  }
};
exports.authorize = authorize;

var authorizeToken = function authorizeToken(req, res, next) {
  var query = req.query;
  var accessToken = query.access_token;
  if (!accessToken) {
    res.status(401);
    return res.send_data({
      code: 400,
      message: '缺少Access Token，未经许可请不要尝试访问本接口。'
    });
  }
  User.findByUnameOrPcode({
    pcode: accessToken
  }).then(function(app) {
    if (!app) {
      res.status(401);
      return res.send_data({
        code: 400,
        message: '该Access Token无效，未经许可请不要尝试访问本接口。'
      });
    }
    if (!app.status) {
      res.status(401);
      return res.send_data({
        code: 400,
        message: '该Access Token已被禁用，未经许可请不要尝试访问本接口。'
      });
    }
    req.station_uuid = app.station_uuid;
    next();
  });
};
exports.authorizeToken = authorizeToken;
